import React, {useRef} from 'react';
import {message, Modal} from 'antd';
import {OpResourcesManager} from "@/services/api-functions";
import {isSuccess} from "@/utils/utils";
import ProTable, {ActionType, ProColumns} from "@ant-design/pro-table";
import {SYS_ENUMS} from "@/utils/constants";

interface CreateFormProps {
  visible: boolean
  title:string
  onCancel: Function
  onSelect: Function
  mul?: boolean
  width?: number
}

const ResourceSelect: React.FC<CreateFormProps> = ({ visible, onCancel, title, onSelect, mul, width}) => {

  const onOk = (select: any)=>{
    if(select){
      onSelect(select)
      if(!!mul){
        onCancel()
      }
    }else {
      message.error('请选择资源')
    }
  }

  const actionRef = useRef<ActionType>();
  const columns: ProColumns[] = [
    {
      title: '标题',
      dataIndex: 'title',
      fixed: 'left',
      ellipsis: true,
    },
    {
      title: '分类',
      dataIndex: 'classification',
      valueEnum: {
        TEMPLATE: {text: '模板'},
        WORKS: {text: '作品'},
        MATERIAL: {text: '素材'},
        ANIMATION: {text: '动画'},
        OTHER: {text: '其他'},
      },
      width: 100,
    },
    {
      title: '状态',
      dataIndex: 'sellingState',
      valueEnum: SYS_ENUMS.RESOURCE_STATUS,
      width: 100,
    },
    {
      title: '设计师',
      dataIndex: 'nickName',
      ellipsis: true,
      hideInSearch: true,
      width: 150,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      hideInSearch: true,
      width: 100,
      hideInForm: true,
      render: (_, record) => [
        <a key="edit" onClick={()=>onOk(record)}>选择</a>,
      ],
    },
  ];

  return (
    <Modal
      destroyOnClose
      width={width??600}
      title={title}
      visible={visible}
      onCancel={() => onCancel()}
      footer={null}
    >
      <ProTable<any, any>
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={false}
        request={async (params) => {

          const query = {...params}

          const {data: {data, total}, code}: any = await OpResourcesManager.pageQuery(query);

          return {data: data || [], success: isSuccess(code), total: isSuccess(code) ? total : 0};
        }}
        columns={columns}
        scroll={{ x: 1300 }}
      />
    </Modal>
  );
};

export default ResourceSelect;
